<template>
  <div>
      <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/main/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/UserManagement'}">用户管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/RoleManagement'}">角色管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/MenuManagement'}">菜单管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/CompanyManagement'}">公司管理</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form :inline="true"  :model="formData">
          <el-form-item label="公司名">
          <el-input placeholder="请输入公司名" v-model="formData.companyName" clearable @clear="queryList"/>
          </el-form-item>
          <el-form-item label="联系电话">
          <el-input placeholder="请输入联系电话" v-model="formData.companyPhone" clearable @clear="queryList"/>
          </el-form-item>
          <el-form-item >
              <el-button type="primary" @click="queryList">搜索</el-button>
              <el-button type="primary" :title="title" @click="add1">新增用户</el-button>
              <!-- <el-button type="danger" @click="removBatch">批量删除</el-button> -->
          </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTableRef">
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="companyQrcode"  width="100">
        <template #default="scope">
          <img :src="`http://localhost:8081/sfzy/${scope.row.companyQrcode}`" alt="公司二维码" style="width: 100%; height: auto;">
      </template>
      </el-table-column>
      <el-table-column prop="companyName" label="公司名称" width="150" />
      <el-table-column prop="companyAddress" label="公司地址" width="150"/>
      <el-table-column prop="companyPhone" label="联系电话" width="100" />
      <el-table-column prop="companyEmail" label="客服邮箱" width="100"/>
      <el-table-column prop="companySynopsis" label="公司简介" width="100" ></el-table-column>
      <el-table-column prop="address" label="操作" >
        <template #default="scope">
          <el-button size="mini" type="primary" :title="title" @click="edit1(scope.row)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" @click="remove(scope.row.id)" >删除</el-button> -->
        </template>
      </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
          <div class="demonstration"></div>
          <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="sizes, prev, pager, next"
          :total="1000"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          />
      </div>

      <el-dialog v-model="dialogFormVisible" :title="title" width="500" @close="cancel">
        <el-form :model="form">
          <el-form-item label="公司二维码" :label-width="formLabelWidth">
            <el-upload drag class="avatar-uploader" method="post" action="http://localhost:8081/sfzy/upload" 
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.imgUrl" :src="`${form.imgUrl}`" class="avatar" />
                <div v-else>
                <el-icon class="avatar-uploader-icon">
                <Plus/>
                </el-icon>
                </div>
                </el-upload>
          </el-form-item>
          <el-form-item label="公司名称" :label-width="formLabelWidth">
            <el-input v-model="aboutUsData.companyName" placeholder="请输入公司名称"/>
          </el-form-item>
          <el-form-item label="公司地址" :label-width="formLabelWidth">
            <el-input v-model="aboutUsData.companyAddress" placeholder="请输入公司地址"/>
          </el-form-item>
          <el-form-item label="联系电话" :label-width="formLabelWidth">
            <el-input v-model="aboutUsData.companyPhone" placeholder="请输入联系电话"/>
          </el-form-item>
          <el-form-item label="客服邮箱" :label-width="formLabelWidth">
            <el-input v-model="aboutUsData.companyEmail" placeholder="请输入客服邮箱"/>
          </el-form-item>
          <el-form-item label="公司简介" :label-width="formLabelWidth">
              <el-input v-model="aboutUsData.companySynopsis" placeholder="请输入公司简介"/>
          </el-form-item>
        
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancle">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref,onMounted,getCurrentInstance,onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { ElUpload } from 'element-plus'; // 引入文件上传组件

const currentInstance = getCurrentInstance()
const {$http}=currentInstance.appContext.config.globalProperties;
const tableData= ref([])
const dialogFormVisible = ref(false)
let title = ref()


const formData = ref({
companyName:'',
type:'',
pageNum:1,
pageSize:5,
ids:[]
})

const aboutUsData= ref({
id:'',
companyQrcode:'', 
companyName:'', 
companyAddress:'',
companyPhone:'',
companyEmail:'',
companySynopsis:'',
})


//图片上传
let form = ref({
    imgUrl: ''
 })
const imageUrl = ref('')
// 图片上传成功的钩子  
const handleAvatarSuccess = (response, uploadFile) => { 
 // 保存相对路径到相关数据对象，以便传给后端
const relativeImagePath = response.data;
 // 拼接完整的图片路径在弹出框中显示
const fullImagePath = `http://localhost:8081/sfzy${response.data}`;
imageUrl.value = URL.createObjectURL(uploadFile.raw); 
form.value.imgUrl=fullImagePath
//传回数据库的路径
aboutUsData.value.companyQrcode = relativeImagePath;
};
onBeforeUnmount(() => { 
   URL.revokeObjectURL(imageUrl.value); 
});

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload = (rawFile) => {
const allowedFormats = ['image/jpeg', 'image/png']; // 允许的文件格式
if (!allowedFormats.includes(rawFile.type)) {
this.$message.error('文件格式必须是 JPG 或 PNG！');
return false;
}
else if (rawFile.size / 1024 / 1024 > 2) {
ElMessage.error('Avatar picture size can not exceed 2MB!')
return false
}
return true
}

// //批量删除
// const selectable = (row) => ![].includes(row.id)
// const handleSelectionChange = (val) => {
//  formData.value.ids = val.map(item => item.id);
// }

onMounted(()=>{
queryList();
});

function handleSizeChange(val) {
    formData.value.pageSize=val
    queryList();
}
function handleCurrentChange(val) {
    formData.value.pageNum=val
    queryList();
}

function queryList(){
$http({
  method:'get',
  url:'http://localhost:8081/sfzy/aboutUs/page',
  params:formData.value
}).then(res=>{
  tableData.value = res.data.data.list;
})
}

// function removBatch(){
//         ElMessageBox.confirm('是否确认删除选中的数据?', '删除', 
//             {
//             confirmButtonText: '确认', // 确认按钮
//             cancelButtonText: '取消', // 取消按钮
//             type: 'warning',// 警告的图标
//             }
//         )
//         .then(() => {
//           const idsArray = formData.value.ids;
//           const idsStr = idsArray.join(",");
//           console.log(idsStr);
        
//            // 点击确认 删除操作
//             $http({
//                 method:'delete',
//                 url:`http://localhost:8081/sfzy/aboutUs?ids=${idsStr}`,
//                 data:{}
//             }).then(res=>{
//                 if(res.status== 200){
//                     ElMessage.success('删除成功')
//                     // 判断当前页是否还有数据，如果没有则将页码减1
//                     if (tableData.value.length === 0 && formData.value.pageNum > 1) {
//                      formData.value.pageNum--;
//                 }
//                 // 清理ids参数
//                 formData.value.ids = [];
//                     queryList();
//                 }else{
//                     ElMessage.error('删除失败')
//                 }
//             })
//         })
//         .catch(() => {
//             ElMessage({
//                 type: 'info',
//                 message: "取消删除操作",
//             })
// })}
      
// function remove(id){
//         ElMessageBox.confirm('是否确认删除选中的数据?', '删除', 
//             {
//             confirmButtonText: '确认', // 确认按钮
//             cancelButtonText: '取消', // 取消按钮
//             type: 'warning',// 警告的图标
//             }
//         )
//         .then(() => {
//            // 点击确认 删除操作
//             $http({
//                 method:'delete',
//                 url:`http://localhost:8081/sfzy/aboutUs/${id}`,
//                  params:{}
//             }).then(res=>{
//                 if(res.status== 200){
//                     ElMessage.success('删除成功')
//                     queryList();
//          }else{
//                     ElMessage.error('删除失败')
//                 }
//             })
//         })
//         .catch(() => {
//             ElMessage({
//                 type: 'info',
//                 message: "取消删除操作",
//             })
// })}


// 新增
function add1(){
title.value = '新增资料'
dialogFormVisible.value=true
form.value.imgUrl=`http://localhost:8081/sfzy/upload${aboutUsData.value.companyQrcode}`

}

function add(){
      $http({
          method:'post',
          url:'http://localhost:8081/sfzy/aboutUs',
          data:aboutUsData.value
      }).then(res=>{
          if(res.data.code== 200){
              ElMessage.success('添加成功')
          }else{
              ElMessage.success('添加失败')
          }
          //关闭添加 对话框
          dialogFormVisible.value= false;
          // 在做一次查询
          queryList();
          cancle();
        })
}
// 修改
function edit1(rowData){
title.value = '修改资料'
dialogFormVisible.value=true
aboutUsData.value=rowData
form.value.imgUrl=`http://localhost:8081/sfzy${aboutUsData.value.companyQrcode}`
}

function edit(){
      $http({
          method:'put',
          url:'http://localhost:8081/sfzy/aboutUs',
          data:aboutUsData.value
      }).then(res=>{
          if(res.data.code== 200){
              ElMessage.success('修改成功')
          }else{
              ElMessage.success('修改失败')
          }
          //关闭添加 对话框
          dialogFormVisible.value= false;
          // 在做一次查询
          queryList();
          cancle();
        })
}

function confirm(){
if(title.value=='新增资料'){
  add();
}else{
  edit();
}
}

//关闭
function cancle(){
dialogFormVisible.value = false;
aboutUsData.value = {
  id:'',
companyQrcode:'', 
companyName:'', 
companyAddress:'',
companyPhone:'',
companyEmail:'',
companySynopsis:''
  }
  queryList();
}
</script>

<style scoped>

</style>
